<?php

namespace App\Service\delivery;
use App\Model\Applet;
use App\Model\AppletPlayletRel;
use App\Model\PlayletEpisodes;
use App\Service\CommicService;
use App\Model\PlayletTag;
use App\Model\Playlet;
use App\Service\queue\DramaService;
use Hyperf\Di\Annotation\Inject;
use Hyperf\Utils\ApplicationContext;
use App\Common\Response\SystemCode;
class PlayletService extends CommicService
{
    const cacheDuration = 60 * 15;

    public function __construct()
    {
        $container = ApplicationContext::getContainer();
        $this->redisService = $container->get(\Hyperf\Redis\Redis::class);

        $this->userAppletIds = $this->getUserAppletInfo();

    }
    const STATUS_ENABLE  = 1;

    public function search(Array $params){


        $keyword     = $params['keyword'] ?? '';
        $status      = $params['status'] ?? '';
        $drama_status      = $params['drama_status'] ?? '';
        $pageSize    = $params['pageSize'] ?? 10;
        $page        = $params['page'] ?? 1;
        $applet_ids     = $params['applet_ids'] ?? '';
        if(empty($applet_ids)){
            return [];
        }
        //获取所拥有的
        if($applet_ids == '1'){
            //获取所有的小程序所绑定的短剧
            $playlet_ids =  AppletPlayletRel::query()->whereIn('applet_id',$this->userAppletIds)->pluck('playlet_id');
        }else{
            $playlet_ids =  AppletPlayletRel::query()->where(['applet_id' => $applet_ids])->pluck('playlet_id');
        }
        $query = Playlet::query()->select(['id','name','cover','thumbnail','introduction','drama_status','is_finish','amount','last_episode_number','last_episode_name','pay_start_cid','pay_type','status','likes_number','share_number','hot_number','created_at','updated_at']);
        if (!empty($playlet_ids)) {
            $query->whereIn('id',$playlet_ids);
        }
        if ($keyword) {
            $query->orWhere([['name', 'like', '%'.$keyword.'%']]);
        }
        if ($status != '') {
            $query->where(['status' => $status]);
        }
        if ($drama_status != '') {
            $query->where(['drama_status' => $drama_status]);
        }
        $models = $query->orderBy('updated_at','desc')->paginate($pageSize,['*'],'page',$page);
        $items = $models->items();
        $selectData = [];
        foreach ($items as $item){
            $data = $item->toArray();
            $data['status_name']  = self::$commonStatus[$item->status];
            $playletEpisodesCount = PlayletEpisodes::query()->where(['playlet_id' => $item->id])->count();
            $data['playet_episodes_count'] = $playletEpisodesCount;
            $data['is_finish_name'] = Playlet::$finishStatus[$item->is_finish];
            $data['pay_type_name'] = Playlet::$payType[$item->pay_type];
            $data['drama_status_name'] = self::$dramaStatus[$item->drama_status];
            $selectData[] =$data;

        }
        $data = $models->toArray();
        $data['data'] = $selectData;
        return $data;
    }

    public function createOrUpdate(Array $postData, bool $is_update = false, Playlet $playletInfo = null){
        $name = $postData['name'];
        $cover = $postData['cover'] ?? '';
        $introduction = $postData['introduction'];
        $is_finish = $postData['is_finish'] ?? 1;
        $amount = $postData['amount'] ?? 0;
        $tag_ids = $postData['tag_ids'] ?? [];
        $producer = $postData['producer'] ?? '';
        $registration_number = $postData['registration_number'] ?? '';
        $registration_number_url = $postData['registration_number_url'] ?? '';
        $last_episode_number = $postData['last_episode_number'] ?? '';
        $pay_start_cid = $postData['pay_start_cid'] ?? '';
        $pay_type = $postData['pay_type'] ?? 1;
        $status = $postData['status'];
        $model = !empty($playletInfo)? $playletInfo : new Playlet();
        $is_check_user = true;
        if($is_update) {
            //修改时判断用户名是否一致
            if ($name == $model->name) {
                $is_check_user = false;
            }
        }
        if($is_check_user){
            $playletInfo = Playlet::query()->where('name',$name)->first();
            if(!empty($playletInfo)){
                return $this->response(SystemCode::SYSTEM_ERROR, '剧集名称已存在');
            }
            $model->name = $name;
        }

        $model->introduction = $introduction;
        $model->is_finish = $is_finish;
        if(!empty($cover)){
            $model->cover = $cover;
        }
        //查询是否有对应的剧集
        if(!empty($last_episode_number) && !empty($model->id)){
            //查询剧集
            $playletEpisodesInfo = PlayletEpisodes::query()->where(['playlet_id' => $model->id,'playlet_number' => $last_episode_number])->select(['playlet_number','playlet_number_name'])->first();
            if(empty($playletEpisodesInfo)){
                return $this->response(SystemCode::SYSTEM_ERROR,'集数不存在');
            }else{
                $model->last_episode_number = $playletEpisodesInfo->playlet_number;
                $model->last_episode_name = $playletEpisodesInfo->playlet_number_name;
            }
        }

        if(!empty($pay_start_cid) && !empty($model->id)){
            //查询剧集
            $playletEpisodesInfo = PlayletEpisodes::query()->where(['playlet_id' => $model->id,'playlet_number' => $pay_start_cid])->select(['playlet_number'])->first();
            if(empty($playletEpisodesInfo)){
                return $this->response(SystemCode::SYSTEM_ERROR,'集数不存在');
            }else{
                $model->pay_start_cid = $pay_start_cid;
            }
        }
        $model->producer = $producer;
        $model->amount = $amount;
        $model->registration_number = $registration_number;
        $model->registration_number_url = $registration_number_url;
        $model->pay_type = $pay_type;
        $model->status = $status;

        if($model->save()){

            //tag 标签 清空这短剧的所有标签
            PlayletTag::query()->where(['playlet_id' => $model->id])->delete();
            if(!empty($tag_ids)){
                foreach ($tag_ids as $tag_id){
                    PlayletTag::create(
                        [
                            'tag_id'   => $tag_id,
                            'playlet_id'   => $model->id,
                        ]
                    );
                }
            }

            return $this->response(SystemCode::SYSTEM_SUCCESS);
        }else{
            return $this->response(SystemCode::SYSTEM_ERROR,'保存错误');
        }
    }


    public function auditDrama(int $id,int $type = 1){

        //获取短剧ID
        $playletData = Playlet::query()->where(['id' => $id])->first();
        if(empty($playletData)){
            return $this->response(SystemCode::SYSTEM_ERROR, '短剧不存在');
        }else{

            if(empty($playletData->producer)){
                return $this->response(SystemCode::SYSTEM_ERROR, '制作方不能为空');
            }
            if(empty($playletData->registration_number)){
                return $this->response(SystemCode::SYSTEM_ERROR, '剧目备案号不能为空');
            }
            if(empty($playletData->registration_number_url)){
                return $this->response(SystemCode::SYSTEM_ERROR, '剧目播放授权材料不能为空');
            }

        }
        //获取这个短剧绑定的第一个小程序，通过此小程序上传短剧
        $appletIds = AppletPlayletRel::query()->where(['playlet_id' => $id])->pluck('applet_id');
        if(empty($appletIds)){
            return $this->response(SystemCode::SYSTEM_ERROR, '短剧没有绑定小程序');
        }

        $appletData = Applet::query()->whereIn('id',$appletIds)->where(['type' => $type])->orderBy('id')->get();
        if(empty($appletData)){
            return $this->response(SystemCode::SYSTEM_ERROR, '小程序不存在');
        }

        //获取小程序下的剧集
        $playletEpisodesData = PlayletEpisodes::query()->where(['playlet_id' => $id])->get();
        if(empty($playletEpisodesData)){
            return $this->response(SystemCode::SYSTEM_ERROR, '该短剧没有剧集');
        }
        //查看这部剧下的是否有未上传媒资
        $errorMsg = [];
        foreach ($playletEpisodesData as $playletEpisodesDatum){

            //微信
            if($type == 1){
                if(empty($playletEpisodesDatum->media_id) || $playletEpisodesDatum->is_upload == 2){

                    $errorMsg[] = $playletEpisodesDatum->playlet_number_name.'没有上传到微信资质';
                }

                if($playletEpisodesDatum->is_upload == 4){

                    $errorMsg[] = $playletEpisodesDatum->playlet_number_name.' 需要重新上传到微信资质中，请重新上传';
                }
            //抖音
            }else{
                if(empty($playletEpisodesDatum->dy_cloud_id) || $playletEpisodesDatum->is_dy_upload == 2){

                    $errorMsg[] = $playletEpisodesDatum->playlet_number_name.'没有上传到抖音资质';
                }

                if($playletEpisodesDatum->is_dy_upload == 4){

                    $errorMsg[] = $playletEpisodesDatum->playlet_number_name.' 需要重新上传到抖音资质中，请重新上传';
                }
            }

        }
        if(!empty($errorMsg)){
            return $this->response(SystemCode::SYSTEM_ERROR, implode(',',$errorMsg));
        }

        $this->dramaService->auditdrama($playletData->id,$appletData[0]->id,$type);

        return $this->response(SystemCode::SYSTEM_SUCCESS);
    }


    public function batchUpload(Array $postData,int $playlet_id,$cover){

        $videoData = $postData['videos'];
        $videoType = $postData['videoType'];    //videoType 1原始视频  2压缩视频
        $errorMeg = [];
        foreach ($videoData as $videoDatum){


            if($videoType == 1){
                if(empty($videoDatum['original_play_url']) || empty($videoDatum['playlet_number'])){
                    $errorMeg[] = $videoDatum['video_name'].' 不存在上传视频或者集数出现问题';
                    continue;
                }
                $original_play_url = $videoDatum['original_play_url'];
            }else{
                if(empty($videoDatum['play_url'])  || empty($videoDatum['playlet_number'])){
                    $errorMeg[] = $videoDatum['video_name'].' 不存在上传视频或者集数出现问题';
                    continue;
                }
                $play_url = $videoDatum['play_url'];
            }

            $playlet_number = (int)$videoDatum['playlet_number'];
            if(empty($playlet_number)){
                $errorMeg[] = $videoDatum['video_name'].' 集数名称有问题';
                continue;
            }
            $playlet_number_name = $this->numToStr($playlet_number);


            if(empty($playlet_number_name)){
                $errorMeg[] = $videoDatum['video_name'].' 集数名称有问题';
                continue;
            }
            $playlet_number_name = '第'.$playlet_number_name.'集';
            $selectData = PlayletEpisodes::query()->where(['playlet_id' => $playlet_id,'playlet_number' => $playlet_number])->first();
            if(!empty($selectData)){
                $selectData->playlet_number_name = $playlet_number_name;
                if($videoType == 1){
                    $selectData->original_play_url = $original_play_url;
                }else{
                    $selectData->play_url = $play_url;
                }


                $selectData->is_upload = 1;
                $selectData->save();
            }else{
               $insertData = new PlayletEpisodes();

                if($videoType == 1){
                    $insertData->original_play_url = $original_play_url;
                }else{
                    $insertData->play_url = $play_url;
                }
                $insertData->playlet_id = $playlet_id;
                $insertData->playlet_number = $playlet_number;
                $insertData->playlet_number_name = $playlet_number_name;
                $insertData->cover = $cover;
                $insertData->amount = 2000;
                $insertData->save();
            }
        }
        if(!empty($errorMeg)){
            return $this->response(SystemCode::SYSTEM_ERROR,implode(',',$errorMeg));
        }else{
            return $this->response(SystemCode::SYSTEM_SUCCESS);
        }



    }
}